// api/chat_api/chat_create.go
package chat_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/service/ai_ser"
	"muziai-server/utils/ocr"
	"muziai-server/utils/res"
)

type ChatCreateRequest struct {
	SessionID uint     `json:"sessionID" binding:"required"`
	Content   string   `json:"content"  binding:"required"`
	ImageList []string `json:"imageList"`
}

func (ch ChatApi) ChatCreateView(c *gin.Context) {
	var cr ChatCreateRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.SSEFailWithError(c, err)
		return
	}

	var session models.SessionModel
	err = global.DB.Preload("UserModel").Preload("RoleModel").
		Take(&session, cr.SessionID).Error
	if err != nil {
		res.SSEFailWithMsg(c, "会话不存在")
		return
	}

	if session.RoleModel.ID == 0 {
		res.SSEFailWithMsg(c, "角色被删除")
		return
	}
	// 创建对话
	chat := models.ChatModel{
		SessionID:   cr.SessionID,
		RoleID:      session.RoleID,
		UserID:      session.UserID,
		UserContent: cr.Content,
	}
	err = global.DB.Create(&chat).Error
	if err != nil {
		res.SSEFailWithMsg(c, "对话创建失败")
		return
	}
	//创建图文
	var chatImageList []models.ChatToImageModel
	for _, s := range cr.ImageList {
		// 这里的s是web路径，需要改成文件路径
		// /uploads/xxx
		// uploads
		if len(s) <= 1 {
			continue
		}
		s1 := s[1:]
		out, err1 := ocr.Ocr(s1)
		if err1 != nil {
			logrus.Warnf("ocr err %s", err1.Error())
			continue
		}
		fmt.Println(s1, out)
		chatImageList = append(chatImageList, models.ChatToImageModel{
			ChatID:          chat.ID,
			ImageUrl:        s1,
			ImageOcrContent: out,
		})

	}
	if len(chatImageList) > 0 {
		err = global.DB.Create(&chatImageList).Error
		if err != nil {
			logrus.Error(err)
		}
	}

	var msgChan chan string
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		err = ch.userservice.UserScope(tx, chat.UserID, -global.Config.AI.ChatScope)
		if err != nil {
			return err
		}
		// 调接口，扣积分
		var gpt ai_ser.ChatGPT
		msgChan, err = gpt.Send(ai_ser.Request{
			RoleID:    chat.RoleID,
			SessionID: chat.SessionID,
			Content:   cr.Content,
			ChatID:    chat.ID,
		})
		return err

	})
	if err != nil {
		res.SSEFailWithError(c, err)
		return
	}
	var aiContnet string
	for s := range msgChan {

		res.SSEOkWithData(c, s)
		aiContnet = aiContnet + s

	}
	err = global.DB.Model(&chat).Update("ai_content", aiContnet).Error
	if err != nil {
		logrus.Error(err)
	}

}
